package com.jindu.producer.finance.controller;


import com.jindu.kernel.page.AlphaPage;
import com.jindu.kernel.result.JsonResult;
import com.jindu.kernel.utils.AlphaBeanUtils;
import com.jindu.kernel.utils.DateUtils;
import com.jindu.kernel.utils.IdGenerator;
import com.jindu.producer.finance.api.UserInterface;
import com.jindu.producer.finance.jpa.ShareJpa;
import com.jindu.producer.finance.model.CContentEntity;
import com.jindu.producer.finance.model.FReplyEntity;
import com.jindu.producer.finance.model.FReportEntity;
import com.jindu.producer.finance.model.FShareEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author jarvis
 * @date 2018/10/18
 */
@Api(description = "分享统计管理", tags = "ShareController", basePath = "/share")
@RestController
@RequestMapping(value = "/share",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ShareController {


    org.slf4j.Logger logger=LoggerFactory.getLogger(ShareController.class);

    @Autowired
    ShareJpa shareJpa;


    @Autowired
    UserInterface userInterface;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据资讯ID，查询资讯或新闻的信息", notes = "返回单个资讯的信息")
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public JsonResult<FShareEntity> get(@RequestParam String id){
        return JsonResult.getSuccessResult(shareJpa.findById(id));
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "【后台】查询 用分析 记录的信息列表", notes = "返回用户分享的列表信息")
    @RequestMapping(value = "getAll",method = RequestMethod.GET)
    public JsonResult<AlphaPage<FShareEntity>> getAll(@RequestParam(value = "pageNo",defaultValue = "0") Integer pageNo,
                                                      @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                                      @RequestParam(value = "shareId",required = false) String shareId){



        Specification querySpecifi = (Specification<FShareEntity>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if(shareId != null){
                predicates.add(criteriaBuilder.equal(root.get("productId"),shareId));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Page<FShareEntity> entities=shareJpa.findAll(querySpecifi,new PageRequest(pageNo, pageSize,sort));

        String shareIds="";
        for (FShareEntity f :entities.getContent() ){
            String id=f.getShareId();
            shareIds+=id;
            shareIds+=",";
        }
        HashMap<String,String> usernames=userInterface.getName(shareIds.toString());

        for (FShareEntity f :entities.getContent()){
            //logger.info(usernames.get(f.getShareId()));
            f.setShareName(usernames.get(f.getShareId()));
        }
        return new AlphaPage<>(entities).toJsonResult();
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "保存分享记录的信息", notes = "保存用户分享的信息")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public JsonResult<FShareEntity> save(@RequestBody FShareEntity shareEntity){

        FShareEntity fShareEntity=shareJpa.findById(shareEntity.getId());

        if(fShareEntity == null){
            shareEntity.setId(IdGenerator.uuid());
            shareEntity.setCreateTime(new Timestamp(DateUtils.getCurrentTime()));
            shareEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            return JsonResult.getSuccessResult(shareJpa.saveAndFlush(shareEntity));
        }else {
            shareEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            BeanUtils.copyProperties(shareEntity,fShareEntity, AlphaBeanUtils.getNullPropertyNames(shareEntity));
            return JsonResult.getSuccessResult(shareJpa.saveAndFlush(fShareEntity));
        }
    }



}
